import { defineStore } from "pinia";
import {
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import type { inspectorType } from "../types";
import {type InspectorResult, login, getInspectorInfo} from "@/api/inspector";
import { setToken, setUserInfo, removeToken, userKey } from "@/utils/auth";
import { useMultiTagsStoreHook } from "./multiTags";

export const useInspectorStore = defineStore({
  id: "inspector",
  state: (): inspectorType => ({
    insId: storageLocal().getItem(userKey)?.insId ?? "",
    insTel: storageLocal().getItem(userKey)?.insTel ?? "",
    insName: storageLocal().getItem(userKey)?.insName ?? "",
    insState:storageLocal().getItem(userKey)?.insState?? "",
  }),

  actions: {
    SET_INS_ID(insId: number) {
      this.insId = insId
    },
    SET_INS_TEL(insTel: string) {
      this.insTel = insTel
    },
    SET_INS_NAME(insName: string) {
      this.insName = insName
    },
    SET_INS_STATE (insState: string) {
      this.insState = insState
    },

    /** 登录 */
    async loginByInsIdByPass(data) {
      console.log("1 loginByAdminCodeByPass");
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          if (res.code === 200) {
            console.log("2 data");
            console.log(res);
            console.log(res.token);
            setToken({
              token: res.data.token
            });
            resolve(res.code);
          } else {
            resolve(res.message);
          }
        });
      });
    },

    /** 获取用户信息 */
    async getInspectorInfoById(data?: object) {
      return new Promise<InspectorResult>((resolve, reject) => {
        getInspectorInfo(data).then(res => {
          if (res.code === 200) {
            setUserInfo({
              insId: res.data.insId,
              insTel: res.data.insTel,
              insName: res.data.insName,
              insState:res.data.insState
            });
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },

    /** 退出登录 */
    logOut() {
      this.insName = "";
      removeToken();
      resetRouter();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      router.push("/login");
    }
  }
});

export function useInspectorStoreHook() {
  return useInspectorStore(store);
}
